$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

$(document).ready(function () {
    if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE8.0"){
        var $moudle = $('#data-moudle');
        var module = $moudle.val();
        var $id = $('#data-id');
        var id = $id.val();
    }else {
        var $body = $('body');
        var module = $body.data('moudle');
        var id = $body.data('id');
    }
    //全局缓存
    var supplierList = {}; //邀请供应商
    var supplierListArray = new Array();//邀请供应商
    var projectUserList =  {};//角色
    var attachmentList = {}; //附件
    var addressData=getAddressData();//获取需要回显得地址数据
    //显示省市区
    showProvince('level','1',null,addressData);//页面初始化(编辑页回显，新增页初始化)
    //选择省市chang事件
    $('#deliveryProvince').bind('change', selProvince);
    $('#deliveryCity').bind('change', selCity);



    //定向非定向选择处理
    var $assureMoney = $('input[name="rulesBo.assureMoney"]');
    var $roleTable = $('#roleTable');
    (function () {
        var checkes = $('input.js-check');
        var $public = $('.fb-zz input');
        $('#checkedDiv').on('change',':radio', function () {
            var needCheck = (this.value == 1);
            checkes.prop('checked',needCheck);
            checkes.attr('disabled',needCheck);
            //定向情况下 公开的相关内容屏蔽，防止提价到后台
            //console.log($public.find(':checkbox'));
            $public.prop('checked',false);
            $public.attr('disabled',!needCheck);
        });



        /*设置制动延迟，次数限制转换清空输入框*/
        $('#setRadio').on('change',':radio', function () {
            var needCheck = (this.value == 1);
            if(needCheck){
                $('#quotationUpperDate').val("");
                $('#maxExtendTime').val("");
                $('#quotationUpperDate').attr('disabled',true);
                $('#maxExtendTime').attr('disabled',true);

            }else{
            $('#lastTime').val("");
            $('#totalNum').val("");
            $('#lastTime').attr('disabled',true);
            $('#totalNum').attr('disabled',true);
            }
        });



        //财务审核控制
        $assureMoney.on('change', function () {
            var money = +$assureMoney.val();
            var $moneyChecks = $roleTable.find('.js-money');
            if(!money){
                $moneyChecks.prop('checked',false);
            }
            $moneyChecks.attr('disabled',!money);
        });
        $assureMoney.trigger('change');
    })();

    //从历史询单创建
    (function(){
        //初始化jqGrid 默认不加载数据
        var jqGrid = null;

        function initJqGrid(){
            return RFQ.jqGrid('#jqGridHis').init({
                url: ctx+'/rfqRequest/rfqRequestList',
                autoLoad:false,
                singleSelect: true,
                /*multiselect: true,*/
                colModel: [
                    {
                        label: '主键',
                        name: 'id',
                        index: 'id',
                        width: 20,
                        key: true,
                        hidden: true
                    },
                    {
                        label: '竟价单号',
                        name: 'unifiedRfqNum',
                        index: 'UNIFIED_RFQ_NUM',
                        width: 20,
                        formatter:selectFormatter
                    },
                    {
                        label: '竞价标题',
                        name: 'title',
                        index: 'TITLE',
                        width: 20,
                    },
                    {
                        label: '创建人',
                        name: 'recCreatorUsername',
                        index: 'REC_CREATOR_USERNAME',
                        width: 20
                    },
                    {
                        label: '创建时间',
                        name: 'recCreateTime',
                        index: 'REC_CREATE_TIME',
                        width: 20
                    },
                    {
                        label: '状态',
                        name: 'type',
                        index: 'TYPE',
                        width: 20,
                        formatter:formatRfqRequestType
                    }
                ],
                postData:{rfqMethod:"DAC"},
                sortname: 'REC_CREATE_TIME',
                sortorder: 'desc',
                pager: "#jqGridHisPager",
                onSelectOneRow:function(rowid,status){
                    var $confirmBtn = $('#myModa1').find('.modal-footer .btn-primary');
                    if(status){
                        $confirmBtn.attr('disabled',false);
                    }else{
                        $confirmBtn.attr('disabled',true);
                    }
                }
            });
        }
        /*$("#jqGridHis").on('change', function () {
            var ids = $('#jqGridHis').jqGrid('getGridParam', 'selrow');
            var $confirmBtn = $('#myModa1').find('.modal-footer .btn-primary');
            $confirmBtn.attr('disabled',false);
        });*/

        $("#btnSearchHis").click(function () {
            var startTime = $('#recCreateTime').val();
            var endTime = $('#recCreateTimeEnd').val();
            //console.log('startTime:'+startTime+',endTime:'+endTime);
            if(startTime>endTime){
                RFQ.warn('创建日期输入异常!');
            }
            jqGrid.reload(form2Json("searchFormHis"));
        });
        //弹窗显示加载数据
        $('#myModa1').on('shown.zui.modal', function() {
            if(!jqGrid){
                jqGrid = initJqGrid();
                jqGrid.reload();
            }
            jqGrid.resize();
        });
        //关闭时清空输入框
        $('#myModa1').on('hide.zui.modal', function () {
            $('#myModa1').find('form')[0].reset();
            $.placeholder();
        });
        /**
         * 竞价单编号链接跳转
         */
        function selectFormatter(cellvalue, options, rawObject) {
            var id = rawObject.id;
            return "<a class='blue' href='"+ctx+"/dacReverseAuction/reverseAuctionDetail?id="+id+"' target='_blank'>"+cellvalue+"</a>";
        }

        window.addHis = function(){
            var ids = $('#jqGridHis').jqGrid('getGridParam', 'selrow');
            //console.log('ids:'+ids);
            if(!ids || !ids.length){
                $('#myModa1').modal('hide');
                return;
            }/* else if(ids.length > 1) {
             $.zui.messager.show('选择的数据超出范围！', {placement: 'center', type: 'warning', icon: 'icon-warning-sign'});
             return;
             } */else {
                $("#rid").val(ids);
                //console.log('rid:'+$("#rid").val());
                var $confirmBtn = $('#myModa1').find('.modal-footer .btn-primary');
                $confirmBtn.attr('disabled',true);
                $.ajax({
                    type: "POST",
                    url: ctx+"/dacReverseAuction/addReverseAuctionByHis",
                    data: {
                        rid: $("#rid").val()
                    },
                    success: function (data) {
                        $confirmBtn.attr('disabled',false);
                        if (data.status == 'success') {
                            $('#myModa1').modal('hide');
                            //成功后跳转到编辑页
                            location.href = ctx+"/dacReverseAuction/toUpdateDacReverseAuction?id="+data.requestId;
                        } else {
                            RFQ.error('sorry,出错了！');
                        }
                    }
                });
            }
        }
    })();
    //END

    //邀请供应商
    (function(){

        var jqGrid = null;
        var sdata = [];
        var $supplistModal = $('#supplistModal');
        var $form = $supplistModal.find('form');
        $supplistModal.on('shown.zui.modal',function(){
            getAttData("#jqGridsup","#jqGridPagersup");

        });

        //关闭时清空输入框
        $supplistModal.on('hide.zui.modal', function () {
            $form[0].reset();
            $.placeholder();
        });
        if (module == 'edit') {

            var isSupplierRequirement = $("#isSupplierRequirement").val();
        } else {
            if ($(":checkbox[name=isSupplierRequirement]").prop("checked")) {
                var isSupplierRequirement = $(":checkbox[name=isSupplierRequirement]").val();
            } else {
                var isSupplierRequirement = '0';
            }

        }
        if (isSupplierRequirement == '0') {
            $("#supplierListJqGrid").jqGrid({
                datatype: 'local',
                rownumbers: true,
                rownumWidth: 50,
                colModel: [
                    {
                        label: 'id',
                        name: 'id',
                        index: 'id',
                        key: true,
                        hidden: true
                    },
                    {
                        label: '合格供应商代码',
                        name: 'supplierCode',
                        index: 'supplierCode',
                        align: 'center'
                    },
                    {
                        label: '特邀供应商名称',
                        name: 'supplierName',
                        index: 'supplierName',
                        align: 'center'
                    },
                    {
                        label: '联系人',
                        name: 'linkmanName',
                        index: 'linkmanName',
                        align: 'center'
                    },
                    {
                        label: '联系电话',
                        name: 'linkmanTelphone',
                        index: 'linkmanTelphone',
                        align: 'center'
                    },
                    {
                        label: '微信状态',
                        name: 'isBindWechat',
                        index: 'isBindWechat',
                        align: 'center'
                    },
                    {
                        label: '操作',
                        name: 'companyId',
                        index: 'companyId',
                        align: 'center',
                        formatter: deleteFormatter
                    }
                ],
                viewrecords: true,
                //sortname: 'userLoginNo',
                //sortorder: 'asc',
                width: "970",
                height: "100%",
                pager: "#supplierListjqGridPager",
                rowNum: 20,//每页显示记录数
                rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
            });
        } else if (isSupplierRequirement == '1') {
            $("#supplierListJqGrid").jqGrid({
                datatype: 'local',
                rownumbers: true,
                rownumWidth: 50,
                colModel: [
                    {
                        label: 'id',
                        name: 'id',
                        index: 'id',
                        key: true,
                        hidden: true
                    },
                    {
                        label: '合格供应商代码',
                        name: 'supplierCode',
                        index: 'supplierCode',
                        align: 'center'
                    },
                    {
                        label: '特邀供应商名称',
                        name: 'supplierName',
                        index: 'supplierName',
                        align: 'center'
                    },
                    {
                        label: '联系人',
                        name: 'answerUsername',
                        index: 'answerUsername',
                        align: 'center'
                    },
                    {
                        label: '联系电话',
                        name: 'linkmanTelphone',
                        index: 'linkmanTelphone',
                        align: 'center'
                    },
                    {
                        label: '微信状态',
                        name: 'isBindWechat',
                        index: 'isBindWechat',
                        align: 'center'
                    },
                    {
                        label: '操作',
                        name: 'companyId',
                        index: 'companyId',
                        align: 'center',
                        formatter: deleteFormatter
                    }
                ],
                viewrecords: true,
                //sortname: 'userLoginNo',
                //sortorder: 'asc',
                width: "100%",
                height: "100%",
                pager: "#supplierListjqGridPager",
                rowNum: 20,//每页显示记录数
                rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
            });
        }
        if (module == 'edit') {
            if (isSupplierRequirement == '0') {

                var supplierListJqGrid = $("#supplierList").val()=="" ? null : JSON.parse($("#supplierList").val());
                //当前存在的数据加入缓存
                if (supplierListJqGrid != undefined && supplierListJqGrid != null) {
                    $.each(supplierListJqGrid, function (i, supplier) {
                        supplierList[supplier.companyId] = supplier;
                    });
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: supplierListJqGrid}).trigger('reloadGrid');

                } else {
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: {}}).trigger('reloadGrid');
                }
            } else if (isSupplierRequirement == '1') {
                var preauditSupplierListJqGrid = $("#preauditSupplierList").val() == "" ? null : JSON.parse($("#preauditSupplierList").val());
                if (preauditSupplierListJqGrid != undefined && preauditSupplierListJqGrid != null) {
                    $.each(preauditSupplierListJqGrid, function (i, preauditSupplier) {
                        supplierList[preauditSupplier.companyId] = preauditSupplier;
                    });
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: preauditSupplierListJqGrid}).trigger('reloadGrid');

                } else {
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: {}}).trigger('reloadGrid');
                }

            }
        }
        $("#supplierListJqGrid").jqGrid('resizeGrid');

        function getAttData(grid,page){
            //启用内存分页
            jqGrid = RFQ.jqGrid(grid).init({
                datatype:"local",
                multiselect: true,
                colModel: [
                    {
                        name: 'companyId',
                        index: 'companyId',
                        key: true,
                        hidden: true
                    },
                    {
                        name: 'isBindWechat',
                        index: 'isBindWechat',
                        hidden: true
                    },
                    {
                        name: 'companyId',
                        index: 'companyId',
                        hidden: true
                    },
                    {
                        label: '供应商U代码',
                        name: 'supplierCode',
                        width: 20,
                    },
                    {
                        label: '供应商名称',
                        name: 'supplierName',
                        width: 20,
                    },
                    {
                        label: '所属类别',
                        name: 'type',
                        width: 20,
                    },
                    {
                        label: '供应商等级',
                        name: 'deviceDealerGrade',
                        width: 20,
                    },
                    {
                        label: '联系人',
                        name: 'linkmanName',
                        width: 20,
                    },
                    {
                        label: '联系电话',
                        name: 'linkmanTelphone',
                        width: 20
                    }
                ],
                pager: page
            });
            $.post(ctx+'/rfqSupplierListNew/rfqSupplierListListNew',{}, function (data) {
                sdata = (data.list||[]).filter(function (item) {
                    return !supplierList[item.companyId];
                });
                jqGrid.loadLocal(sdata);
            },'json')
        }

        $("#btnSearch").click(function () {
            var validJson = {};
            $form.find(':text,select').each(function () {
                this.value && (validJson[this.name] = this.value);
            });
            var searchData = sdata.filter(function (item) {
                var isValid = true;
                for(var key in validJson){
                    if(!isValid) return false;
                    if(key == 'supplierName' || key == 'supplierCode' || key == 'type'){
                        isValid = ~item[key].indexOf(validJson[key]);//模糊匹配
                    }else{
                        isValid = (item[key] == validJson[key]);
                    }
                }
                return isValid;
            });
            jqGrid.loadLocal(searchData);
        });


        $supplistModal.on('click','.js-confirm', function () {
            var rows = $('#jqGridsup').jqGrid("getGridParam", "selarrrow");
            var renderHTML = [];
            $.each(rows,function(i,r){
                if(supplierList[r]) return true;
                var rowData = $('#jqGridsup').jqGrid('getRowData',r);//获取选中行的数据（单行）
                //数据加入缓存
                supplierList[r] = rowData;
            });
            RFQ.d(supplierList);
            var rowNum = 0;
            supplierListArray.splice(0, supplierListArray.length);//清空数组
            $.each(supplierList, function (i, d) {
                supplierListArray[rowNum] = d;
                rowNum++;
            });

            $("#supplierListJqGrid").jqGrid("clearGridData");
            $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: supplierListArray}).trigger('reloadGrid');
            $('#supplistModal').modal('hide');
        });

        //删除
        $('#gview_supplierListJqGrid').on('click','.order-del-btn',function(){
            var id = $(this).data("id");
            $(this).parent().parent("tr").remove();
            //从缓存里面删除
            delete supplierList[id];
            supplierListArray.splice(0, supplierListArray.length);//清空数组
            var rowNum = 0;
            $.each(supplierList, function (i, d) {
                supplierListArray[rowNum] = d;
                rowNum++;
            });
            $("#supplierListJqGrid").jqGrid("clearGridData");
            $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: supplierListArray}).trigger('reloadGrid');
        });

    })();
    function deleteFormatter(cellvalue, options, rawObject) {
        //DOM操作
        var deleteTmp = '<a class="order-del-btn" data-id="' + rawObject.companyId + '"><i class="red icon icon-trash"></i>&nbsp; 删除</a>';
        return deleteTmp;
    }

    //END
    //END





    //角色设置
    (function(){
        var jqGrid = null;
        var roleData = [];
        var $myModaphone = $('#myModaphone');
        var $form = $myModaphone.find('form');
        $myModaphone.on('shown.zui.modal',function(){
            getAttData("#jqGridphone","#jqGridPagerphone");
        });
        $myModaphone.on('hide.zui.modal', function () {
            $form[0].reset();
        });
        function getAttData(grid,page){
            jqGrid = RFQ.jqGrid(grid).init({
                datatype:"local",
                multiselect: true,
                colModel: [
                    {
                        label: '主键',
                        name: 'userId',
                        width: 20,
                        key: true,
                        hidden: true
                    },
                    {
                        label: '工号',
                        name: 'jobCode',
                        width: 20,
                    },
                    {
                        label: '姓名',
                        name: 'userName',
                        width: 20,
                    },
                    {
                        label: '所属科室',
                        name: 'userOffice',
                        width: 20,
                    },
                    {
                        label: '职位',
                        name: 'userTitle',
                        width: 20
                    }
                ],
                pager: page
            });
            $.post(ctx+ '/rfqProjectUserNew/rfqProjectUserListNew',{}, function (data) {
                roleData = (data.list||[]).filter(function (item) {
                    return !projectUserList[item.userId];
                });
                jqGrid.loadLocal(roleData);
            },'json');
        }

        $("#roleSearch").click(function () {
            var validJson = {};
            $form.find(':text,select').each(function () {
                this.value && (validJson[this.name] = this.value);
            });
            var searchData = roleData.filter(function (item) {
                var isValid = true;
                for(var key in validJson){
                    if(!isValid) return false;
                    if(key == 'userOffice' || key == 'userName'){
                        isValid = ~item[key].indexOf(validJson[key]);//模糊匹配
                    }else{
                        isValid = (item[key] == validJson[key]);
                    }
                }
                return isValid;
            });
            jqGrid.loadLocal(searchData);
        });

        //DOM操作
        var rowIndex = 0;
        var rowTmp = '<tr id="puser_{userId}"> <td>{index}</td> <td>{jobCode}</td> <td>{userName}</td> <td>{userOffice}</td> <td>{userTitle}</td> <td><input name="" type="checkbox"></td> <td><input name="" type="checkbox"></td> <td><input class="js-money" name="" type="checkbox"></td> <td><a class="order-del-btn" data-id="{userId}"><i class="icon icon-trash red"></i>&nbsp; 删除</a></td> </tr>';

        //if(module == 'edit'){
        //当前存在的数据加入缓存
        $('#roleTable tbody').find('tr').each(function () {
            var tmp = {};
            $(this).find('td').each(function () {
                var $this = $(this);
                var name = $this.data('name');
                if(!name) return true;
                tmp[name] = $this.data('value');
            });
            projectUserList[tmp.userId] = tmp;
            rowIndex ++;
        });
        //}
        RFQ.d(projectUserList);

        $('#myModaphone').on('click','.js-confirm', function () {
            var rows = $('#jqGridphone').jqGrid("getGridParam", "selarrrow");
            var renderHTML = [];
            $.each(rows,function(i,r){
                if(projectUserList[r]) return true;
                var rowData = $('#jqGridphone').jqGrid('getRowData',r);//获取选中行的数据（单行）
                rowData.index = rowIndex + 1;
                renderHTML.push(rowTmp.format(rowData));
                rowIndex ++;
                projectUserList[r] = rowData;
            });
            $roleTable.find('tbody').append(renderHTML.join(''));
            var money = +$assureMoney.filter(':checked').val();
            if(!money){
                $roleTable.find('.js-money').attr('disabled',true);
            }
            $('#myModaphone').modal('hide');
            resetSeq();
            RFQ.d(projectUserList);
        });

        //删除
        $('#roleTable').on('click','.order-del-btn',function(){
            var id = $(this).data("id");
            $(this).parent().parent("tr").remove();
            delete projectUserList[id];
            rowIndex >0 && rowIndex--;
            resetSeq();
            RFQ.d(projectUserList);
        });

        //重新设置序号
        function resetSeq(){
            var $tds = $('#roleTable tbody').find('tr td:first-child');
            $tds.each(function (i,el) {
                $(this).html(i+1);
            });
        }
    })();
    //END

    var editor,editor2,editor3,editorMemo;
    //商务与技术条款
    (function(){

        <!--富文本JS-->
        KindEditor.ready(function(K) {
            editor = K.create('textarea#contentSimple', {
                resizeType : 1,
                allowPreviewEmoticons : false,
                allowImageUpload : false,
                items : []
            });
        });
        KindEditor.ready(function(K) {
            editor2 = K.create('textarea#contentSimple2', {
                resizeType : 1,
                allowPreviewEmoticons : false,
                allowImageUpload : false,
                items : []
            });
        });
        KindEditor.ready(function(K) {
            editor3 = K.create('textarea#contentSimple3', {
                resizeType : 1,
                allowPreviewEmoticons : false,
                allowImageUpload : false,
                items : []
            });
        });
        KindEditor.ready(function(K) {
            editorMemo = K.create('textarea#memo', {
                resizeType : 1,
                allowPreviewEmoticons : false,
                allowImageUpload : false,
                items : []
            });
        });
        var jqGrid = null;
        var jqGrid2 = null;

        $('#myModaBL').on('shown.zui.modal',function(){
            jqGrid = getAttData("BL","#jqGrid","#jqGridPager");
        });
        $('#myModaTL').on('shown.zui.modal',function(){
            jqGrid2 = getAttData("TL","#jqGrid1","#jqGridPager1");
        });
        function getAttData(type,grid,page){
            return RFQ.jqGrid(grid).init({
                url:ctx+ '/rfqLibTerms/rfqLibTermsList',
                multiselect: true,
                colModel: [
                    {
                        label: '序号',
                        name: 'termId',
                        index: 'TERM_ID',
                        width: 40,
                        key: true,
                        hidden:true
                    },
                    {
                        label: '条款名称',
                        name: 'title',
                        index: 'TITLE',
                        width: 80
                    },
                    {
                        label: '条款内容',
                        name: 'content',
                        index: 'CONTENT',
                        width: 110
                    },
                    {
                        label: '备注',
                        name: 'remark',
                        index: 'REMARK',
                        width: 110
                    }
                ],
                postData:{type:type},
                prmNames: {
                    id: 'termId'//请求参数映射，如默认参数为id，实际参数为myId则可在此映射
                },
                sortname: 'TERM_ID',
                sortorder: 'asc',
                pager:page
            });
        }

        $('#myModaBL').on('click','.js-confirm', function () {
            var rows = $('#jqGrid').jqGrid("getGridParam", "selarrrow");
            var renderHTML = [];
            $.each(rows,function(i,r){
                var rowData = $('#jqGrid').jqGrid('getRowData',r);//获取选中行的数据（单行）
                renderHTML.push("条款名："+rowData.title+"；条款内容："+rowData.content);
            });
            editor3.html(editor3.html() + renderHTML.join('<br/>'));
            $('#myModaBL').modal('hide');
        });

        $('#myModaTL').on('click','.js-confirm', function () {
            var rows = $('#jqGrid1').jqGrid("getGridParam", "selarrrow");
            var renderHTML = [];
            $.each(rows,function(i,r){
                var rowData = $('#jqGrid1').jqGrid('getRowData',r);//获取选中行的数据（单行）
                renderHTML.push("条款名："+rowData.title+"；条款内容："+rowData.content);
            });
            editor2.html(editor2.html() + renderHTML.join('<br/>'));
            $('#myModaTL').modal('hide');
        });
    })();
    //END


    //附件上传
    //BEGIN
    (function () {
        var $myModa2 = $('#myModa2');
        var $attachmentList1 = $('#attachmentList1');
        var $attachmentList2 = $('#attachmentList2');
        var rowTmp = '<tr data-clone="orginal"> <td data-order="true">1</td> <td>{originalFilename}</td> <td>{fileSize}KB</td> <td>{fileDeclaration}</td> <td><a href="javascript:;" data-key="{downloadFilename}_{type}" class="text-danger order-del-btn"><i class="icon-trash"></i> 删除</a></td> </tr>';



        $('button.attachmentBtn').on('click', function () {
            $myModa2.data('_type',$(this).data('type'));
        });

        //附件
        var types=[".jpg",".jpeg",".gif",".png",".doc",".docx",".xls",".xlsx",".pdf"];
        var maxSize=104857600;//100M，单位:B
        //初始化flash插件
        if(navigator.appName == "Microsoft Internet Explorer"){
            $("#myModa2").on('show.zui.modal', function () {
                //初始化flash插件
                initPlupload2(maxSize,types);
                //关闭时清理页面
                initEvent();
            });
        }else {
            //初始化flash插件
            initPlupload(maxSize,types);
            //关闭时清理页面
            initEvent();
        }

        //当前存在的数据加入缓存
        $('#attachmentList1 tr,#attachmentList2 tr').each(function () {
            var tmp = {};
            $(this).find('[data-name]').each(function () {
                var $this = $(this);
                var name = $this.data('name');
                if(!name) return true;
                tmp[name] = $this.data('value');
            });
            attachmentList[tmp.downloadFilename + '_'+tmp.type] = tmp;
        });

        $myModa2.on('click','.js-confirm', function () {
            var type = $myModa2.data('_type');
            var data = $myModa2.data('_result');

            if(data==undefined || data==''){
                RFQ.error("您还没选择文件！");
            }
            if(!data.fileSize){
                RFQ.warn('文件未上传完成，请重新上传');
                return false;
            }

            data.type = type;
            data.fileDeclaration = $myModa2.find('textarea').val();
            var $container = (type == 'R' ? $attachmentList2:$attachmentList1);
            attachmentList[data.downloadFilename + '_'+data.type] = data;
            $container.append(rowTmp.format(data));
            $myModa2.modal('hide');
            resetSeq($container);
        });

        //删除
        $attachmentList1.on('click','.order-del-btn',deleteHandle);
        $attachmentList2.on('click','.order-del-btn',deleteHandle);

        function deleteHandle(){
            var $this = $(this);
            var key = $(this).data("key");
            $this.parent().parent("tr").remove();
            delete attachmentList[key];
            resetSeq($this.closest('tbody'));
            RFQ.d(attachmentList);
        }

        //重新设置序号
        function resetSeq($tbody){
            var $tds = $tbody.find('tr td:first-child');
            $tds.each(function (i,el) {
                $(this).html(i+1);
            });
        }
    })();
    //END

    //常用地址设置
    (function(){
        var jqGrid = null;
        /*$('#prouser').click(function(){
         getAttData("#jqGridphone","#jqGridPagerphone");

         });*/
        $('#myModa8').on('shown.zui.modal', function() {
            if(!jqGrid){
                jqGrid = initAddreJqGrid();
                jqGrid.reload();
            }
            jqGrid.resetSelection();
            jqGrid.resize();
        });

        function initAddreJqGrid(grid,page){
            return RFQ.jqGrid('#AddreJqGrid').init({
                url:ctx+ '/rfqCommonAddress/rfqCommonAddressList',
                autoLoad:false,
                singleSelect: true,
                colModel: [
                    {
                        label: '主键',
                        name: 'id',
                        index: 'ID',
                        key: true,
                        hidden: true
                    },
                    {
                        label: '省id',
                        name: 'deliveryProvinceCode',
                        index: 'DELIVERY_PROVINCE_CODE',
                        hidden: true
                    },
                    {
                        label: '省',
                        name: 'deliveryProvince',
                        index: 'DELIVERY_PROVINCE',
                    },
                    {
                        label: '市id',
                        name: 'deliveryCityCode',
                        index: 'DELIVERY_CITY_CODE',
                        hidden: true
                    },
                    {
                        label: '市',
                        name: 'deliveryCity',
                        index: 'DELIVERY_CITY',
                    },
                    {
                        label: '区id',
                        name: 'deliveryAreaCode',
                        index: 'DELIVERY_AREA_CODE',
                        hidden: true
                    },
                    {
                        label: '区',
                        name: 'deliveryArea',
                        index: 'DELIVERY_AREA',
                    },
                    {
                        label: '具体地址',
                        name: 'deliveryAddress',
                        index: 'DELIVERY_ADDRESS',
                    },
                    {
                        width: 80,
                        label: '操作',
                        name: '',
                        index: '',
                        sortable:false,
                        formatter: optFormatter
                    }
                ],
                sortname: 'ID',
                sortorder: 'desc',
                pager: '#AddreJqGridPager',
            });
        }

        function optFormatter(cellvalue, options, rawObject) {
            var detailBtn = '<span class="ml5"><a  href="javascript:delCommonAddress(\'' + rawObject.id + '\')"><i class="icon icon-trash red"></i> 删除</a></span>';
            return detailBtn;
        };


        window.delCommonAddress =  function(id){
            var data = {
                id : id
            };
            RFQ.post(ctx+'/rfqCommonAddress/delRfqCommonAddress',data,function(data){
                RFQ.jqGrid('#AddreJqGrid').reload();
            });
        };

        window.addAddress = function(){
            var ids = $('#AddreJqGrid').jqGrid('getGridParam', 'selarrrow');
            //console.log('ids:'+ids);
            if(ids.length==0){
                $('#myModa8').modal('hide');
                return;
            }else {
                var rowData = $('#AddreJqGrid').jqGrid('getRowData',ids);//获取选中行的数据（单行）
                //赋值
                selProvince("1",rowData);
                $("#deliveryAddress").val(rowData.deliveryAddress);
                $('#myModa8').modal('hide');
            }
        }
    })();
    //END


    //采购组织维护常用地址
    (function(){
        $('#modalAddress').on('shown.zui.modal', function() {
            $("#deliveryProvince2").val("");
            $("#deliveryCity2").val("");
            $("#deliveryArea2").val("");
            $("#deliveryAddress2").val("");
            //显示省市区
            showProvince('level','1','2');
            //选择省市chang事件
            $('#deliveryProvince2').bind('change', function(){selProvince('2')} );
            $('#deliveryCity2').bind('change', function(){selCity('2')});
        });

        window.ajaxToAddData = function(){
            var data = {
                deliveryProvince : $("#deliveryProvince2").val(),
                deliveryCity : $("#deliveryCity2").val(),
                deliveryArea : $("#deliveryArea2").val(),
                deliveryAddress : $("#deliveryAddress2").val()
            };
            RFQ.post(ctx+'/rfqCommonAddress/saveRfqCommonAddress',data,function(data){
                $('#modalAddress').modal('hide');
                RFQ.jqGrid('#AddreJqGrid').reload();
            });
        }
    })();
    //END
// 添加历史物料
    (function(){

        var jqGrid = null;
        var sdata = [];
        var $itemsModal = $('#itemsModal');
        var $form = $itemsModal.find('form');

        var jqGrid = null;

        function initItemJqGrid(){
            return RFQ.jqGrid('#jqGriditem').init({
                url: ctx+'/rfqRequestItem/rfqRequestItemList',
                autoLoad:false,
                multiselect: true,
                colModel: [
                    {
                        label: '主键',
                        name: 'id',
                        index: 'ID',
                        width: 20,
                        key: true,
                        hidden: true
                    },
                    {
                        label: '询单主表ID',
                        name: 'requestId',
                        index: 'REQUEST_ID',
                        width: 20,
                        hidden: true
                    },
                    {
                        label: '物料代码',
                        name: 'materialNo',
                        index: 'MATERIAL_NO',
                        width: 20,
                    },
                    {
                        label: '物料名称',
                        name: 'materialName',
                        index: 'MATERIAL_NAME',
                        width: 20,
                    },
                    {
                        label: '型规',
                        name: 'character',
                        index: 'CHARACTER',
                        width: 20
                    },
                    {
                        label: '单位',
                        name: 'unit',
                        index: 'UNIT',
                        width: 20
                    },
                    {
                        label: '备注',
                        name: 'memo',
                        index: 'MEMO',
                        width: 20,
                    }
                ],
                sortname: 'SEQ',
                sortorder: 'ASC',
                pager: "#jqGridPageritem"
            });
        }

        $("#itembtnSearch").click(function () {
            jqGrid.reload(form2Json("itemSearchForm"));
        });

        //弹窗显示加载数据
        $('#itemsModal').on('shown.zui.modal', function() {
            if(!jqGrid){
                jqGrid = initItemJqGrid();
                jqGrid.reload();
            }
            jqGrid.resize();
        });


        $itemsModal.on('click','.js-confirm', function () {
            var rows = $('#jqGriditem').jqGrid("getGridParam", "selarrrow");
            $.each(rows,function(i,r){

                 var rowData = $('#jqGriditem').jqGrid('getRowData',r);//获取选中行的数据（单行）
                RFQ.d(rowData);
                var url = ctx+'/dacReverseAuction/dacRequestItemList';
                $.post(url,{requestId:rowData.requestId,id:rowData.id}, function (data) {
                    parseItems(data.list||[]);
                    $itemsModal.modal('hide');
                },'json');

            });

        });

    })();
    //END


    //表单提交
    (function(){
        var $requestId = $('#requestId');
        var $requestRfqNum = $('#requestRfqNum');
        var $myModa9 = $('#myModa9');
        var $myModa6 = $('#myModa6');



        //表单操作按钮
        $('#dataform').on('click','.js-form-btn',function(){

           /* //表单验证
            if(checkReverseActionForm()){
                return;
            }*/

            var $this = $(this);
            var type = $this.data('type');
            if(type==1 || type== 3 || type==4){ //1 保存  4 发布 3 预览 统一提交表单
                var extras = fecthExtraParams();
                var url = '';
                if(type == 1){
                    url = (module=='edit'?'saveDacReverseAuction/edit': 'saveDacReverseAuction/add');
                }else if(type == 3){
                    url = 'dacReverseAuctionPreview';
                }else if(type == 4){
                    url = (module=='edit'?'updateDacReverseAuctionData': 'saveDacReverseAuctionPreview/add');
                    if(!validate2000(editor)){
                        RFQ.error("报名要求最多输入2000字符！");
                        return;
                    }
                    if(!validate2000(editor3)){
                        RFQ.error("商务条款最多输入2000字符！");
                        return;
                    }
                    if(!validate2000(editor2)){
                        RFQ.error("技术条款最多输入2000字符！");
                        return;
                    }
                    if(!validate2000(editorMemo)){
                        RFQ.error("竞价单备注最多输入2000字符！");
                        return;
                    }
                }
                //提交前保存物料临时数据
                var $requestItemTable = $('#datatable-requestItemTable');
                var rfqDTable = $requestItemTable.data('_rfqDTable');
                if(rfqDTable.options.beforePagination.call(rfqDTable)){ //临时数据保存成功
                    rfqDTable.load();
                    RFQ.form('#dataform').ajaxSubmit(ctx+ '/dacReverseAuction/'+url,extras, function (data) {
                        //这里防止二次提交保存两条数据
                        if(module!='edit' && (type == 1 || type == 4 )){
                            var obj = data.obj;
                            if(!obj.requestId) return;
                            $requestId.val(obj.requestId);
                            $requestRfqNum.val(obj.requestNo);
                            module = 'edit';
                            id = obj.requestId;
                        }
                        if(type == 1){ //保存成功
                            var messageList1 = data.obj.messageList1;
                            if (messageList1 != null && messageList1 != "") {
                                RFQ.warn('保存成功![' + messageList1 + "]");
                            } else {
                                RFQ.info('保存成功!');
                            }
                            window.location.href = ctx + '/dacReverseAuction/toUpdateDacReverseAuction?id=' + data.obj.requestId;
                        }
                        if(type == 4){ //保存成功并发布
                            var messageList1 = data.obj.messageList1;
                            if (messageList1 != "" && messageList1 != null) {
                                RFQ.warn(messageList1)
                            }
                            RFQ.renderText('#myModa6',data.obj);
                            $myModa6.data('id',data.obj.requestId);
                            $myModa6.modal('show');
                            //输出审批流
                            $("#appro").empty();
                            var appList = data.obj.appList;
                            if(appList!="" && appList!=null){
                                $("#appro").append("<option value='0'>无需审批</option>");
                                $.each(appList || [], function (i, val) {
                                    var type = "";
                                    if (val.type == "1") {
                                        type = "标准";
                                    } else if (val.type == "2") {
                                        type = "灵活";
                                    } else {
                                        type = "未知";
                                    }
                                    $("#appro").append("<option value=" + val.number + ',' + val.type + ">" + type + ":" + val.wfDefineName + "</option>");
                                });
                            }else{
                                $("#appro").attr("disabled",true);
                                $("#appro").append("<option value='0'>无有效审批</option>");
                            }
                        }
                        if(type == 3){
                            var messageList1 = data.obj.messageList1;
                            console.log('messageList1' + messageList1);
                            if (messageList1 != "" && messageList1 != null) {
                                RFQ.warn(messageList1);
                            }
                            RFQ.openLinkInBlank(ctx+'/dacReverseAuction/toDacReverseAuctionPreview');
                        }
                    });
                }
            }else{ //删除
                //RFQ.info('删除！');
                RFQ.confirm('确认要删除吗？', function () {
                    RFQ.post(ctx+'/dacReverseAuction/deleteReverseAuction',{id:id}, function () {
                        RFQ.info('操作成功');
                        location.href=ctx+'/rfqRequest/init';
                    });
                });
            }
        });


       /* 公开竞价排名公开竞价价格单选框*/
       $('#checkPublic').on('change',':radio', function () {
            $checkPublic = $(this);
            var type = $checkPublic.data("type");
           if(type == "viewPriceBillboardFlag"){
               $('input[name="rulesBo.viewPriceBillboardFlag"]').val("1");
               $('input[name="rulesBo.viewPriceBillboardFlag"]').removeAttr("disabled");
               $('input[name="rulesBo.viewLowerestPriceFlag"]').val("");
               $('input[name="rulesBo.viewLowerestPriceFlag"]').attr("disabled",true);
           }else {
               $('input[name="rulesBo.viewLowerestPriceFlag"]').val("1");
               $('input[name="rulesBo.viewLowerestPriceFlag"]').removeAttr("disabled");
               $('input[name="rulesBo.viewPriceBillboardFlag"]').val("");
               $('input[name="rulesBo.viewPriceBillboardFlag"]').attr("disabled",true);
           }
       })



        //发布摸态框按钮事件绑定
        $myModa6.on('click','.modal-footer a',function(){
            var type = $(this).data('type');
            var selAudit = $('#appro').val();
            if(type == 1){ //确认提交
                var procDefType;
                if (selAudit != 0) {   //选择审批
                    procDefType = selAudit.split(",")[1];
                    if (procDefType == 2) {   //灵活流程
                        $('#myModa6').modal('hide');
                        $('#myRole').modal('show');
                        return;
                    } else {
                        var $confirmBtn = $myModa6.find('.modal-footer .btn-primary');
                        $confirmBtn.attr('disabled', true);
                        postforData([]);
                    }
                } else {
                    var $confirmBtn = $myModa6.find('.modal-footer .btn-primary');
                    $confirmBtn.attr('disabled', true);
                    postforData([]);
                }
            }else if(type == 2){ //返回修改
                location.href=ctx+'/dacReverseAuction/toUpdateDacReverseAuction?id='+id;
            }
        });

        //抓取额外参数
        function fecthExtraParams(){
            //组装额外参数 选取的供应商以及角色
            var extras = {};
            if(!$.isEmptyObject(supplierList)){
                var index = 0,tmp;
                for(var key in supplierList){
                    tmp = supplierList[key];
                    extras['supplierList['+index+'].seq'] = index+1;
                    extras['supplierList['+index+'].companyId'] = tmp.companyId;
                    extras['supplierList['+index+'].supplierCode'] = tmp.supplierCode;
                    extras['supplierList['+index+'].supplierName'] = tmp.supplierName;
                    extras['supplierList['+index+'].linkmanName'] = tmp.linkmanName;
                    extras['supplierList['+index+'].answerUsername'] = tmp.linkmanName;//适配报名表联系人
                    extras['supplierList['+index+'].linkmanTelphone'] = tmp.linkmanTelphone;
                    extras['supplierList['+index+'].isBindWechat'] = tmp.isBindWechat;
                    index++;
                }
            }
            if(!$.isEmptyObject(projectUserList)){
                var index = 0,tmp;
                for(var key in projectUserList){
                    tmp = projectUserList[key];
                    extras['projectUserList['+index+'].seq'] = index+1;
                    extras['projectUserList['+index+'].userId'] = tmp.userId;
                    extras['projectUserList['+index+'].userOffice'] = tmp.userOffice;
                    extras['projectUserList['+index+'].jobCode'] = tmp.jobCode;
                    extras['projectUserList['+index+'].userName'] = tmp.userName;
                    extras['projectUserList['+index+'].userTitle'] = tmp.userTitle;
                    //获取选中的权限
                    var $checks = $('#puser_' + key).find(':checkbox');
                    extras['projectUserList['+index+'].viewQx'] = $checks.eq(0).prop('checked')?1:0;
                    extras['projectUserList['+index+'].optionQx'] = $checks.eq(1).prop('checked')?1:0;
                    extras['projectUserList['+index+'].caiwuQx'] =  $checks.eq(2).prop('checked')?1:0;
                    index++;
                }
            }

            //checkbox处理
            $(':checkbox').each(function () {
                var $this = $(this);
                var name = $this.data('name');
                if(!name) return true;
                extras[name] = $this.prop('checked')?1:0;
            });


            //富文本e
            extras['requestBo.requestBusiTerms'] = editor3.html();
            extras['requestBo.requestTecTerms'] = editor2.html();
            extras['preauditBo.requirementDesc'] = editor.html();
            extras['requestBo.memo'] = editorMemo.html();//竞价单备注



            //组装附件信息
            if(!$.isEmptyObject(attachmentList)){
                var index = 0,tmp;
                for(var key in attachmentList){
                    tmp = attachmentList[key];
                    extras['attachmentsList['+index+'].seq'] = index+1;
                    extras['attachmentsList['+index+'].type'] = tmp.type;
                    extras['attachmentsList['+index+'].downloadFilename'] = tmp.downloadFilename;
                    extras['attachmentsList['+index+'].fileSize'] = tmp.fileSize;
                    extras['attachmentsList['+index+'].originalFileType'] = tmp.originalFileType;
                    extras['attachmentsList['+index+'].originalFilename'] = tmp.originalFilename;
                    extras['attachmentsList['+index+'].downloadUrl'] = tmp.downloadUrl;
                    extras['attachmentsList['+index+'].fileDeclaration'] = tmp.fileDeclaration;
                    index++;
                }
            }
            return extras;
        }

    })();
    //END

    $('input[name="requestBo.title"]').keyup(function () {
        $('#_title').html($(this).val());
    });
    $('input[name="requestBo.planNo"]').keyup(function () {
        $('#_planNo').html($(this).val());
    });
});
//ajax提交方法
function postforData(rowDataLists) {
    var id = $('#myModa6').data('id');
    var publicBiddingFlag = $('input[name="rulesBo.publicBiddingFlag"]').prop('checked') ? 1 : 0;
    RFQ.post(ctx + '/dacReverseAuction/saveDacReverseAuctionPreview/publish', {
        id: id,
        selAudit: $('#appro').val(),
        publicBiddingFlag: publicBiddingFlag,
        rowDataLists: JSON.stringify(rowDataLists)
    }, function (data) {
        location.href = ctx + '/rfqRequest/init';
    });
}
/**
 * 显示初始省市区信息
 */
function showProvince(key1,value1,flag,rowData) {
    //flag：''询单常用地址 '2' 采购组织常用地址维护
    //console.log('key1:'+key1)
    //key值获取变量的方法
    var data = {},key=key1;
    data[key]=value1;
    var province = "#deliveryProvince";
    if(flag=='2') province = "#deliveryProvince2";
    $.ajax({
        type: "POST",
        url: ctx+"/rfqRequest/refreshArea",
        data: data,
        cache: false,
        success: function (data) {
            if (null != data && "" != data) {
                $(province).empty();
                $.each(data, function (i, val) {
                    $(province).append("<option value=" + val.code+','+val.name + ">" + val.name + "</option>");
                });
                /*for (var i = 0; i < data.length; i++) {
                 $("#deliveryProvince").append("<option value=" + data[i].code + ">" + data[i].name + "</option>");
                 }*/
                selProvince(flag,rowData);
            } else {
                $.zui.messager.show('sorry,区域信息刷新出错了！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
            }
        }
    });
}

/**
 * 选择省
 */
function selProvince(flag,rowData){ //rowData需要回显得数据
    var province = "#deliveryProvince";
    var city = "#deliveryCity";
    var area = "#deliveryArea";
    if(flag=='2'){
        var province = "#deliveryProvince2";
        var city = "#deliveryCity2";
        var area = "#deliveryArea2";
    }
    if(rowData!=null){
        $(province).val(rowData.deliveryProvinceCode+','+rowData.deliveryProvince);
    }
/*    var code = $(province).val().substring(0,6);*/
    var code = $(province).val().substring(0,6);
    //console.log('province:'+code)
    $.ajax({
        type: "POST",
        url: ctx+"/rfqRequest/refreshArea",
        data: {
            pCode: code
        },
        cache:false,
        success: function (data) {
            if (null!=data && ""!=data) {
                //清空市区select
                $(city).empty();
                $(area).empty();
                $.each(data, function(i,val){
                    $(city).append("<option value=" + val.code+','+val.name + ">" + val.name + "</option>");
                });
                if(rowData!=null){
                    $(city).val(rowData.deliveryCityCode+','+rowData.deliveryCity);
                }
                selCity(flag,rowData);
            } else {
                $.zui.messager.show('sorry,出错了！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
            };
        }
    });
}

/**
 * 选择市
 */
function selCity(flag,rowData){//rowData需要回显得数据
    var city = "#deliveryCity";
    var area = "#deliveryArea";
    if(flag=='2'){
        var city = "#deliveryCity2";
        var area = "#deliveryArea2";
    }
    var code = $(city).val().substring(0,6);
    //console.log('city:'+code)
    $.ajax({
        type: "POST",
        url: ctx+"/rfqRequest/refreshArea",
        data: {
            pCode: code
        },
        cache:false,
        success: function (data) {
            if (null!=data && ""!=data) {
                //清空区select
                $(area).empty();
                $.each(data, function(i,val){
                    $(area).append("<option value=" + val.code+','+val.name + ">" + val.name + "</option>");
                });
                if(rowData!=null){
                    $(area).val(rowData.deliveryAreaCode+','+rowData.deliveryArea);
                }
            } else {
                $.zui.messager.show('sorry,出错了！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
            }
        }
    });
}

//清空file按钮
function excelClicke() {
    if (file.outerHTML) {
        file.outerHTML = file.outerHTML;
    } else {
        file.value = "";
    }



}





//解析转换后台传来的数据
function parseItems(data){
    RFQ.d(data);
    var parseData = {};
    var $requestItemTable = $('#datatable-requestItemTable');
    var rfqDTable = $requestItemTable.data('_rfqDTable');
    var mappingnames = rfqDTable.mappingNames;
    rfqDTable.acceptChanges();
    var rows =  rfqDTable.rows;
    if(data){
        //计算序号
        var beginNum = (rfqDTable.page-1) * (rfqDTable.rowNum);
        $.each(data, function (i,d) {
            d['id']="";
            rows.push(rfqDTable.renderRow(beginNum+i,d));
        });
        rfqDTable._load(rows);
        var sum = getTotalPrice();
        $('#totalPrice').html(sum.toFixed(2));
    }else{

    }
}

//计算总价
function getTotalPrice(){
    var $requestItemTable = $('#datatable-requestItemTable');
    var sum = 0;
    $requestItemTable.find("input[data-name='requestAmount']").each(function(){
        var $this = $(this);
        var $tr = $this.closest('tr');
        var requestAmount = +this.value;
        var salePrice = +$tr.find('input[data-name="salePrice"]').val();
        !requestAmount && (requestAmount = 0);
        !salePrice && (salePrice = 0);
        sum += (requestAmount*salePrice);
    });
    return sum;
}
//表单验证
function checkReverseActionForm() {
    // 移除所有提示信息
    $('.tipInfo').remove();
    var flag=true;
    // 遍历表单中所有的text并校验
    $('input.v-text').each(function(){
        var s=$(this).Bvalidate({
            // 此处同java的override，可以覆盖默认定义的正则表达式
//                    positiveFloatReg:/^([1-9]\d+|\d)(\.\d{1,2})?$/

        });
        flag=flag&&s;
    });
    if(flag){
        //验证通过执行
        return false;
//                alert('验证成功');
    }else{ // 校验不通过根据类型提示相应信息
        $.each($('#validate-form').find('input[type="text"]'), function(i, key) {
            if($('#validate-form').find('input[type="text"]').eq(i).hasClass('error')){
              /* var msg = setTipInfo($(this).attr("valtype"))
                RFQ.error(msg);
                return true;*/
                $(this).after('<span class="tipInfo red"><i class="icon icon-remove-sign"></i> '+setTipInfo($(this).attr("valtype"))+'</span>')

            }
        });
        return true;
    };

}

